﻿using Neodynamic.SDK.ZPLPrinter;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace ZPLPrint
{
    public partial class Frm_LXYSYYL : Form
    {
        PrintDocument printDocument;
        CommonHelper CommonH = new CommonHelper();

        public Frm_LXYSYYL()
        {
            InitializeComponent();
            // 这里的printDocument对象可以通过将PrintDocument控件拖放到窗体上来实现，注意要设置该控件的PrintPage事件。
            printDocument = new PrintDocument();
            printDocument.DocumentName = "测试";
            printDocument.PrintPage += new PrintPageEventHandler(this.printDocument_PrintPage);
        }

        /// <summary>
        /// 打印内容页面布局
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void printDocument_PrintPage(object sender, PrintPageEventArgs e)
        {
            var g = e.Graphics; //获得绘图对象
            string myDir = Directory.GetCurrentDirectory() + @"\temp\Image0.PNG";

            using (FileStream fs = new FileStream(myDir, FileMode.Open, FileAccess.Read))
            {
                Image img = Image.FromStream(fs);
                Rectangle rect = new Rectangle(0, 0, img.Width, img.Height);
                g.DrawImage(img, rect);
            }
            g.Dispose();//释放掉该资源
        }

        /// <summary>
        /// 打印纸设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void FileMenuItem_PageSet_Click(object sender, EventArgs e)
        {
            PageSetupDialog pageSetupDialog = new PageSetupDialog();
            pageSetupDialog.Document = printDocument;
            pageSetupDialog.ShowDialog();
        }
        /// <summary>
        /// 打印机设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void FileMenuItem_PrintSet_Click(object sender, EventArgs e)
        {
            PrintDialog printDialog = new PrintDialog();
            printDialog.Document = printDocument;
            printDialog.ShowDialog();
        }
        /// <summary>
        /// 预览功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void FileMenuItem_PrintView_Click(object sender, EventArgs e)
        {
            PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog { Document = printDocument };
            try
            {
                printPreviewDialog.ShowDialog();
            }
            catch (Exception excep)
            {
                MessageBox.Show(excep.Message, "打印出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 打印功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void FileMenuItem_Print_Click(object sender, EventArgs e)
        {
            PrintDialog printDialog = new PrintDialog { Document = printDocument };
            if (printDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    printDocument.Print();
                }
                catch (Exception excep)
                {
                    MessageBox.Show(excep.Message, "打印出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    printDocument.PrintController.OnEndPrint(printDocument, new PrintEventArgs());
                }
            }
        }
        ZPLPrinter zplPrinter = new ZPLPrinter("License Owner", "License Key");

        private void button1_Click(object sender, EventArgs e)
        {
            //Prepare ZPLPrinter
            PrepareZPLPrinter();
            string Print = CommonH.getBoxFlie(Application.StartupPath + @"\template\Test.prn");

            DisplayRenderOutput(zplPrinter.ProcessCommands(Print, Encoding.UTF8));
        }
        private void PrepareZPLPrinter()
        {
            //ZPLPrinter acts as a virtual printer...
            //Some ZPL commands could upload labels, graphics, fonts 
            //and /or modify global printer settings
            //that can be used by other commands...
            //So, by Resetting the printer before processing ZPL commands
            //will make the printer to clear settings and any resources uploaded by previous commands
            zplPrinter.PowerOnReset();

            //Set printer DPI
            //The DPI value to be set must match the value for which 
            //the ZPL commands to be processed were created!!!
            zplPrinter.Dpi = float.Parse("203");

            //set label size
            zplPrinter.LabelWidth = (float)10 * zplPrinter.Dpi;
            zplPrinter.LabelHeight = (float)10 * zplPrinter.Dpi;

            zplPrinter.ForceLabelWidth = false;
            zplPrinter.ForceLabelHeight = false;


            //Apply antialiasing?
            zplPrinter.AntiAlias = true;

            //Set image or doc format for output rendering 
            zplPrinter.RenderOutputFormat = (RenderOutputFormat)Enum.Parse(typeof(RenderOutputFormat), "PNG");

            //Set rotation for output rendering
            zplPrinter.RenderOutputRotation = (RenderOutputRotation)Enum.Parse(typeof(RenderOutputRotation), "None");

            //Set Ribbon Color
            zplPrinter.RibbonColor = ColorToHex(Color.Black);

            //Set Label BackColor
            zplPrinter.LabelBackColor = ColorToHex(Color.White);

            //Set Background Image
            zplPrinter.BackgroudImageFile = "";

            //Set Watermark Image
            zplPrinter.WatermarkImageFile = "";
            zplPrinter.WatermarkOpacity = 50;

            //Set Thumbnail Size
            //zplPrinter.ThumbnailSize = 300;
        }
        private string ColorToHex(Color c)
        {
            return string.Format("{0}{1}{2}{3}",
                Convert.ToString(c.A, 16).PadLeft(2, '0'),
                Convert.ToString(c.R, 16).PadLeft(2, '0'),
                Convert.ToString(c.G, 16).PadLeft(2, '0'),
                Convert.ToString(c.B, 16).PadLeft(2, '0'));
        }
        private void DisplayRenderOutput(List<byte[]> buffer)
        {
            // the buffer param contains the binary output of the ZPL rendering result
            // The format of this buffer depends on the RenderOutputFormat property setting
            if (buffer != null && buffer.Count > 0)
            {
                //temp folder for holding thermal label images
                this.imageViewer1.Clear();
                string myDir = Directory.GetCurrentDirectory() + @"\temp\";
                if (Directory.Exists(myDir) == false) Directory.CreateDirectory(myDir);
                DirectoryInfo di = new DirectoryInfo(myDir);
                foreach (FileInfo file in di.GetFiles()) file.Delete();

                try
                {
                    //save images on disk 
                    for (int i = 0; i < buffer.Count; i++)
                    {
                        File.WriteAllBytes(myDir + "Image" + i.ToString().PadLeft(buffer.Count, '0') + "." + zplPrinter.RenderOutputFormat.ToString(), buffer[i]);
                    }
                    //preview them
                    this.imageViewer1.LoadImages(myDir, zplPrinter.RenderOutputFormat.ToString());

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}
